#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>

void print_help(char *name);

int main(int argc, char **argv)
{
	int					rv = -1;
	int					clifd = -1;
	int					port = -1;
	char				*ip;
	char				buf[128] = "hello world";
	struct sockaddr_in	servaddr;


	struct option		opts[] = {                                 // 参数解析
		{"port", required_argument,	NULL, 'P'},
		{"ip", required_argument, NULL, 'i'},
		{"help", required_argument, NULL, 'h'}
	};

	while( (rv = getopt_long(argc,argv, "p:i:hc::", opts, NULL)) != -1)   // 命令行参数解析
	{
		switch(rv)
		{
			case 'p' :
						port = atoi(optarg);     //  参数获取 端口
						break;
			case 'i' :
						ip = optarg;           //  获取ip
						break;
			case 'h' :
						print_help(argv[0]);
						return 0;
			case 'c' : 
						memcpy(buf, optarg, sizeof(optarg));
						break;

		}

	}	

	
	clifd = socket(AF_INET, SOCK_STREAM, 0);            //  socket   
	if(clifd == -1)
	{
		printf(" socket error : %s \n", strerror(errno));
		return -1;
	}
	
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	inet_aton(ip, &servaddr.sin_addr);

	rv = connect(clifd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	if( rv == -1)
	{
		printf("connect error : %s \n ", strerror(errno));
		goto clear;		
	}
	
	rv = write(clifd, buf, strlen(buf));
	if(rv < 0 )
	{
		printf("write error : %s \n", strerror(errno));
		goto clear;

	}

	rv = read(clifd, buf, sizeof(buf));
	if(rv < 0)
	{
		printf("write error : %s \n", strerror(errno));
		goto clear;
	}

	printf("connect succed [%s:%d], \n\n read succed ：%s \n", ip, port, buf);

	memset(buf, 0, sizeof(buf));
	printf(" write :: \n ");
	fgets(buf, sizeof(buf), stdin);            //在标准输入获取字符串
	while( strstr(buf, "exit") == NULL )       //当输入 exit 时退出循环
	{
		rv = write(clifd, buf, strlen(buf));   //向服务器写字符串
		if(rv < 0 )
		{
			printf("write error : %s \n", strerror(errno));
			goto clear;

		}
		
		memset(buf, 0, sizeof(buf));
		rv = read(clifd, buf, sizeof(buf));     //  接收服务器返回的字符串
		if(rv < 0)
		{
			printf("read error : %s \n", strerror(errno));
			goto clear;
		}
		else if(rv == 0)
		{
			printf("connect error :%s \n ", strerror(errno));
			goto clear;
		}

		printf(" read :%s.\n", buf);
		memset(buf, 0, sizeof(buf));
		printf(" write :: \n ");
		fgets(buf, sizeof(buf), stdin);

	}

clear:
	close(clifd);

	return 0;

}


void print_help(char *name)
{

	printf("--port -p : ipv4 port \n --ip -i : addr \n");


}






